#include "kdcabstractkprocessjob.h"

KDCAbstractKProcessJob::KDCAbstractKProcessJob( QObject *parent )
 : KDCJob( parent ), p_niceLevel( -100 )
{
	p_process = new KProcess( this );
	p_process->setOutputChannelMode( KProcess::MergedChannels );
	connect( p_process, SIGNAL( finished( int , QProcess::ExitStatus ) ), this, SLOT( processFinished( int , QProcess::ExitStatus ) ) );
	connect( p_process, SIGNAL( readyReadStandardOutput() ), this, SLOT( readyReadProcessOutput() ) );
	connect( p_process, SIGNAL( readyReadStandardError() ), this, SLOT( readyReadProcessError() ) );
}

KDCAbstractKProcessJob::~KDCAbstractKProcessJob()
{
	if ( p_process )
	{
		p_process->disconnect();
		if ( p_process->state() == QProcess::Running )
			p_process->close();
		delete p_process;
	}
}

void KDCAbstractKProcessJob::addArgument( const QString& arg, const QString& value, bool replace )
{
	int idx = p_arguments.indexOf( arg );
	if ( idx == -1 )
	{
		p_arguments << arg;
		if ( !value.isEmpty() )
			p_arguments << value;
	}
	else
		if ( !value.isEmpty() )
		{
			if ( replace )
				p_arguments[ idx + 1 ] = value;
			else
				p_arguments[ idx + 1 ] += value;
		}
}

void KDCAbstractKProcessJob::clearArguments()
{
	p_arguments.clear();
	p_process->clearProgram();
	p_process->clearEnvironment();
}

void KDCAbstractKProcessJob::setProgram( const QString& program )
{
	p_program = program;
}

void KDCAbstractKProcessJob::setWorkingDirectory( const QString& dir )
{
	p_process->setWorkingDirectory( dir );
}

QString KDCAbstractKProcessJob::program() const
{
	return p_program;
}

QStringList KDCAbstractKProcessJob::arguments() const
{
	return p_arguments;
}

KProcess* KDCAbstractKProcessJob::process() const
{
	return p_process;
}

void KDCAbstractKProcessJob::setStandardOutputFile( const QString& file )
{
	if ( !file.isEmpty() )
		p_process->setStandardOutputFile( file );
}

void KDCAbstractKProcessJob::setStandardInputFile( const QString& file )
{
	if ( !file.isEmpty() )
		p_process->setStandardInputFile( file );
}

void KDCAbstractKProcessJob::readyReadProcessError()
{

}

void KDCAbstractKProcessJob::setNiceLevel( int level )
{
	p_niceLevel = level;
}

int KDCAbstractKProcessJob::niceLevel() const
{
	return p_niceLevel;
}

QByteArray KDCAbstractKProcessJob::extract( QByteArray& data, int start, char end )
{
	QByteArray res;
	char byte = data.at( start );
	while ( byte != end )
	{
		res.append( byte );
		++start;
		byte = data.at( start );
	}
	return res.trimmed();
}
